package com.projects.modular.system.controller;

import com.projects.modular.system.service.SseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/api/sse")
public class SseController {

    private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();

    @Autowired
    private SseService sseService;

    /**
     * 客户端连接SSE端点
     * @param clientId 客户端标识
     * @return SseEmitter对象
     */
    @GetMapping("/connect/{clientId}")
    public SseEmitter connect(@PathVariable String clientId) {
        // 创建SseEmitter，设置超时时间为0（永不超时）或设置具体时间如30分钟
        SseEmitter emitter = new SseEmitter(0L);
        
        // 将emitter存储到map中
        emitters.put(clientId, emitter);
        
        // 注册超时和错误回调
        emitter.onTimeout(() -> {
            emitters.remove(clientId);
            emitter.complete();
        });
        
        emitter.onError(throwable -> {
            emitters.remove(clientId);
            emitter.complete();
        });
        
        // 连接建立时发送欢迎消息
        try {
            emitter.send(SseEmitter.event()
                .name("connect")
                .data("Connected to SSE server"));
        } catch (IOException e) {
            emitters.remove(clientId);
            emitter.complete();
        }
        sseService.addEmitter(clientId, emitter);
        System.out.println("Client " + clientId + " connected");
        sseService.broadcastMessage("connect", "Client " + clientId + " connected");
        return emitter;
    }

    /**
     * 断开连接
     * @param clientId 客户端标识
     */
    @GetMapping("/disconnect/{clientId}")
    public void disconnect(@PathVariable String clientId) {
        SseEmitter emitter = emitters.remove(clientId);
        if (emitter != null) {
            emitter.complete();
        }
    }
}
